package service

import (
    "fmt"
    "github.com/gogf/gf/encoding/gjson"
    "github.com/gogf/gf/frame/g"
    "github.com/gogf/gf/net/ghttp"
    "github.com/gogf/gf/os/gtime"
    "github.com/gogf/gf/util/gconv"
    "github.com/gogf/gf/util/grand"
    "time"
    "webserver/app/define"
    "webserver/library/utils"
)

var (
    HiFuturesQuoteService = &hiFuturesQuoteService{}
)

type hiFuturesQuoteService struct {}

func (s *hiFuturesQuoteService) CheckAllFuturesQuote(r *ghttp.Request) error {
    symbolList := `{
        "TA": "PTA",
        "OI": "菜油",
        "RS": "菜籽",
        "RM": "菜粕",
        "ZC": "动力煤",
        "WH": "强麦",
        "JR": "粳稻",
        "SR": "白糖",
        "CF": "棉花",
        "RI": "早籼稻",
        "MA": "甲醇",
        "FG": "玻璃",
        "SF": "硅铁",
        "SM": "锰硅",
        "CY": "棉纱",
        "AP": "苹果",
        "CJ": "红枣",
        "UR": "尿素",
        "SA": "纯碱",
        "PF": "短纤",
        "PK": "花生",
        "V": "PVC",
        "P": "棕榈油",
        "B": "豆二",
        "M": "豆粕",
        "I": "铁矿石",
        "JD": "鸡蛋",
        "L": "塑料",
        "PP": "聚丙烯",
        "FB": "纤维板",
        "Y": "豆油",
        "C": "玉米",
        "A": "豆一",
        "J": "焦炭",
        "JM": "焦煤",
        "CS": "玉米淀粉",
        "EG": "乙二醇",
        "RR": "粳米",
        "EB": "苯乙烯",
        "LH": "生猪",
        "FU": "燃料油",
        "SC": "原油",
        "AL": "沪铝",
        "RU": "橡胶",
        "ZN": "沪锌",
        "CU": "沪铜",
        "AU": "黄金",
        "RB": "螺纹钢",
        "WR": "线材",
        "PB": "铅",
        "AG": "白银",
        "BU": "沥青",
        "HC": "热卷",
        "SN": "锡",
        "NI": "镍",
        "SP": "纸浆",
        "NR": "20号胶",
        "SS": "不锈钢",
        "LU": "低硫燃油",
        "BC": "国际铜"
    }`
    if j, err := gjson.DecodeToJson(symbolList); err != nil {
        return err
    } else {
        var rows map[string]string
        if err := j.Scan(&rows); err != nil {
            return err
        }
        for k, v := range rows {
            err = s.GetFuturesQuoteOfAllHistory(r, k, v)
            fmt.Println("CheckAllFuturesQuote::Row::", gtime.Now(), k, v, err)
            times := grand.N(2,6)
            time.Sleep(time.Duration(times) * time.Second)
        }
    }
    return nil
}

func (s *hiFuturesQuoteService) GetFuturesQuoteOfAllHistory(r *ghttp.Request, code string, name string) error {
    //http://stock2.finance.sina.com.cn/futures/api/json.php/IndexService.getInnerFuturesDailyKLine?symbol=M0
    ajaxReq := new(define.AjaxReq)
    ajaxReq.Url = "http://stock2.finance.sina.com.cn/futures/api/json.php/IndexService.getInnerFuturesDailyKLine?symbol=" + code + "0"
    ajaxReq.Header = []*define.AjaxHeaderReq{
        {Key: "Content-Type", Val: "application/json"},
        {Key: "Referer", Val: "http://vip.stock.finance.sina.com.cn"},
        {Key: "User-Agent", Val: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36 Edg/97.0.1072.55"},
    }

    rsp, err := utils.HttpGet(ajaxReq.Url, ajaxReq.Header)
    if err != nil {
        return err
    }
    //ret, err := utils.HttpResultToJson(rsp)
    //if err != nil {
    //    return err
    //}

    var yesterdayRow []interface{}
    var todayRow []interface{}

    priceLow := 0.0
    priceHigh := 0.0

    if j, err := gjson.DecodeToJson(rsp); err != nil {
        return err
    } else {
        var rows []interface{}
        if err := j.Scan(&rows); err != nil {
            return err
        }

        for i, row := range rows {
            var cols []interface{}
            err = gconv.Scan(row, &cols)
            if err != nil {
                return err
            }
            //近N年数据
            //if len(cols) > 5 && gtime.New(cols[0]).Year() > gtime.Now().Year() - 10 {
            if len(cols) > 5 {
                price := gconv.Float64(cols[4])
                if priceLow == 0.0 {
                    priceLow = price
                }
                if priceHigh == 0.0 {
                    priceHigh = price
                }

                if price < priceLow {
                    priceLow = price
                }
                if price > priceHigh {
                    priceHigh = price
                }

                if i == len(rows) - 2 {
                    yesterdayRow = cols
                } else if i == len(rows) - 1 {
                    todayRow = cols
                }
            }
        }
    }

    hiFuturesPriceLineField := define.HiFuturesPriceLineField{
        PriceLow: priceLow,
        PriceHigh: priceHigh,
        PriceUpdateDt: gtime.Now(),
        LineLow: priceLow + ((priceHigh - priceLow) / 10),
        LineHigh: priceHigh - ((priceHigh - priceLow) / 10),
    }

    if yesterdayRow != nil && todayRow != nil && len(yesterdayRow) > 5 && len(todayRow) > 5 {
        yesterdayPrice := gconv.Float64(yesterdayRow[4])
        todayPrice := gconv.Float64(todayRow[4])
        if hiFuturesPriceLineField.LineHigh > 0 && yesterdayPrice > 0 && todayPrice > 0 {
            mailBody := fmt.Sprintf("代码：%v，最新价：%v，历史最高：%v，历史最低：%v，UP线：%v，DOWN线：%v",
                code,
                todayPrice,
                hiFuturesPriceLineField.PriceHigh,
                hiFuturesPriceLineField.PriceLow,
                hiFuturesPriceLineField.LineHigh,
                hiFuturesPriceLineField.LineLow,
            )
            if yesterdayPrice >= hiFuturesPriceLineField.LineHigh && todayPrice < hiFuturesPriceLineField.LineHigh {
                // 从高位10%区间下降掉出
                g.Log().Line().Println("[GetFuturesQuoteOfAllHistory]", code + "-" + name + "，从高位10%区间下降掉出", mailBody)
                _ = EmailService.Notice(code + "-" + name + "，从高位10%区间下降掉出", mailBody)
            } else if yesterdayPrice <= hiFuturesPriceLineField.LineLow && todayPrice > hiFuturesPriceLineField.LineLow {
                // 从低位10%区间上升进入
                g.Log().Line().Println("[GetFuturesQuoteOfAllHistory]", code + "-" + name + "，从低位10%区间上升进入", mailBody)
                _ = EmailService.Notice(code + "-" + name + "，从低位10%区间上升进入", mailBody)
            } else if todayPrice > hiFuturesPriceLineField.LineHigh {
                // 位于高位10%区间
                g.Log().Line().Println("[GetFuturesQuoteOfAllHistory]", code + "-" + name + "，位于高位10%区间", mailBody)
                _ = EmailService.Notice(code + "-" + name + "，位于高位10%区间", mailBody)
            } else if todayPrice < hiFuturesPriceLineField.LineLow {
                // 位于低位10%区间
                g.Log().Line().Println("[GetFuturesQuoteOfAllHistory]", code + "-" + name + "，位于低位10%区间", mailBody)
                _ = EmailService.Notice(code + "-" + name + "，位于低位10%区间", mailBody)
            }
        }
    }

    //err = HiFuturesAlertConfService.SavePriceLine(r, code, &hiFuturesPriceLineField)
    return err
}

func (s *hiFuturesQuoteService) GetFuturesQuoteOfLast(r *ghttp.Request, code string) error {

    return nil
}
